import { useEffect, useState } from "react"
import { useNavigate } from "react-router-dom"
import { useDispatch, useSelector } from 'react-redux'
import { setChat } from '../store/index'
import $ from '../axios'
export default function Index() {
    const Navigate = useNavigate()
    const dispatch = useDispatch()
    const [ChatList, setChatList] = useState([])
    const [Chatlist1, setChatList1] = useState([])
    const Myid = useSelector(data => { return data.Myid })
    const getList = async () => {
        await $.get('/getUser').then(val => {
            setChatList(val.data.data)
            setChatList1(val.data.data1)
        })
    }
    useEffect(() => {
        if (!sessionStorage.getItem('token')) {
            Navigate('/Login')
            return
        }
        getList()
    }, [])
    return (
        <div>
            <div style={{ width: '100%', height: '50px', lineHeight: '50px' }}>
                <h2 style={{ textAlign: 'center' }}>消息中心</h2>
            </div>
            <div style={{ height: '100%', width: '90%', marginLeft: '5%' }}>
                {ChatList.filter(ele1 => { return ele1._id !== Myid }).map((ele, index) => {
                    return <div onClick={() => {
                        Navigate('/ChatXiang')
                        dispatch(setChat(ele))
                        sessionStorage.setItem('heData', JSON.stringify(ele))
                    }} style={{ display: 'flex', marginBottom: '20px' }} key={index}>
                        <img src={'../public/' + ele.img} width={50} height={50} style={{ borderRadius: '50%' }}></img>
                        <div style={{ marginLeft: '10px' }}>
                            <p style={{ fontSize: '14.5px' }}>{ele.name}</p>
                            <p style={{ marginTop: '10px', fontSize: '16px' }}>
                                {Chatlist1.filter(ele2 => { return ele2.acceptId === ele._id || ele2.sendId === ele._id }).length !== 0
                                    ? Chatlist1.filter(ele2 => { return ele2.acceptId === ele._id || ele2.sendId === ele._id })[Chatlist1.filter(ele2 => { return ele2.acceptId === ele._id || ele2.sendId === ele._id }).length - 1].content
                                    : '暂无消息'}
                            </p>
                        </div>
                    </div>
                })}
            </div>
        </div>
    )
}